# pycryptodome
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad


def aes_encrypt(key, iv, text):
    cipher = AES.new(key=key, mode=AES.MODE_CBC, iv=iv)
    text_pad = pad(text, AES.block_size)  # 填充
    cipher_text = cipher.encrypt(text_pad)  # 将填充的数据进行加密
    cipher_text_base64 = base64.b64encode(cipher_text).decode()  # 将加密后的数据进行base64转换，在网络上传输
    return cipher_text_base64


def aes_decrypt(key, iv, cipher_text_base64):
    cipher = AES.new(key=key, mode=AES.MODE_CBC, iv=iv)
    decrypt_text_base64 = base64.b64decode(cipher_text_base64)
    decrypt_text = cipher.decrypt(decrypt_text_base64)
    decrypt_text_unpad = unpad(decrypt_text, AES.block_size).decode()
    return decrypt_text_unpad


if __name__ == '__main__':
    key = b'0123456789abcdef'
    iv = b'0123456789abcdef'

    # 加密方式 CBC 需要iv 偏移量
    # ECB 不需要 iv 偏移量

    text = '今天星期一'.encode()
    cipher_text_base64 = aes_encrypt(key, iv, text)
    decrypt_text = aes_decrypt(key, iv, cipher_text_base64)
    print(decrypt_text)
